<template>
  <div class="bigbox">
    <!-- 页面头部搜索栏 -->
    <div class="topbox">
      <el-form ref="form" label-position="left" label-width="80px">
          <el-row :gutter="20">
              <el-col :span="5">
                <el-form-item label="用电企业">
                  <FilterSelect2
                      v-model="orgNo" 
                      @updateModelValue="changeqiye"
                      :optionlist="qiyelist"
                      :valuekey="{ name: 'bizOrgName', value: 'bizOrgNo' }"
                    ></FilterSelect2>
                </el-form-item>
              </el-col>
              <el-col :span="6" style="margin-top: 4px;display: flex;">
                <el-radio-group v-model="radio3" size="small" style="margin-right: 20px;">
                  <el-radio-button label="日"></el-radio-button>
                  <el-radio-button label="月"></el-radio-button>
                  <el-radio-button label="年"></el-radio-button>
                </el-radio-group>
                <template v-if="radio3=='日'">
                <el-date-picker
                size="small"
                  v-model="value1"
                  style="flex: 1;"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日">
                </el-date-picker>
              </template>
              <template v-else-if="radio3=='月'">
                <el-date-picker
                size="small"
                  v-model="value2"
                  value-format="yyyy-MM"
                  style="flex: 1;"
                  type="month"
                  placeholder="选择月">
                </el-date-picker>
              </template>
              <template v-else>
                <el-date-picker
                size="small"
                  v-model="value3"
                  value-format="yyyy"
                  style="flex: 1;"
                  type="year"
                  placeholder="选择年">
                </el-date-picker>
              </template>
              </el-col>
              <el-col :span="13" style="text-align: right;">
                <el-form-item label="">
                  <el-button size="small" type="primary" @click="submit">查 询</el-button>
                </el-form-item>
              </el-col>
          </el-row>
      </el-form>
    </div>
    <!-- 盒子主体 -->
    <div class="bodybox">
      <!-- 封装导出/刷新/调节功能 -->
      <div style="display: flex; justify-content: space-between;">
        <div>企业负荷分析</div>
        <div><TopTitle @command="command" @daochu="daochu" @shuaxin="shuaxin"></TopTitle></div>
      </div>
      <!-- 图表盒子 -->
      <div class="tubiaobox">
        
        <div class="zexian" ref="zexian"></div>
      </div>
      <!-- 表格盒子 -->
      <div class="tablebox">
        <template>
              <el-table
                :data="tableData"
                border
                ref="table"
                highlight-current-row
                @current-change="handleCurrentChange"
                :header-cell-style="{'text-align':'center',background:'#f5f5f5'}"
                v-loading="loading"
                :size="iissize"
                height="calc(100% - 20px)"
                style="width: 100%">
                <el-table-column 

                width="200"
                prop="companyName"
                label="用电企业">
                </el-table-column>
                <template v-if="dayyearmonth=='日'">
                  <el-table-column
                  v-for="(item,index) in timeArray"
                  :key="index"
                  width="110"
                  :prop="'load'+(index+1)"
                  :label="item"
                  align="right">
                </el-table-column>
                </template>
                <template v-else-if="dayyearmonth=='月'">
                  <el-table-column
                  v-for="(item,index) in montharr"
                  :key="index"
                  width="110"
                  :prop="'load'+(index+1)"
                  :label="item.toString()"
                  align="right">
                </el-table-column>
                </template>
                <template v-else-if="dayyearmonth=='年'">
                  <el-table-column
                  v-for="(item,index) in monthArray"
                  :key="index"
                  width="110"
                  :prop="'load'+(index+1)"
                  :label="item"
                  align="right">
                </el-table-column>
                </template>
              </el-table>
            </template>
      </div>
    </div>
  </div>
</template>

<script>
import { saveAs } from 'file-saver'
import TopTitle from '@/components/TopTitle/index.vue'
import { getuserlistapi,getdanweifhapi,exportdanweifhapi } from '@/api/analysis'
import  {timeArray,getDaysInMonth ,monthArray} from '@/utils/array'
import * as echarts from 'echarts';
export default {
  name: 'CallPoliceIndex',
  components: {
    TopTitle
  },
  data() {
    return {
      tableData:[],
      iissize: 'medium',
      value1: '',
      value2: '',
      value3:'',
      orgNo:'',
      qiyelist: [],
      radio3: '日',
      timeArray: timeArray,
      montharr: [],
      monthArray:monthArray,
      dayyearmonth: '日',
      loading: false,
      echartarray:[]
    };
  },

  async mounted() {

    const res = await getuserlistapi()
    this.qiyelist = res.data.list
    this.qiyelist.unshift({bizOrgName:'全部',bizOrgNo:''})
    this.orgNo = this.$store.state.statistics.userbizOrgNo ? this.$store.state.statistics.userbizOrgNo : this.qiyelist[0].bizOrgNo
    this.gettime()
    this.getmonth()
    await this.gettanglist()
    // this.getechartsdata() 
    this.getzheecharts()
  },

  methods: {
    // 企业下拉
    changeqiye(val) {
      this.$store.commit('setuserobject', val)
    },
    // 获取表格数据
    async gettanglist() {
      this.loading=true
      const res = await getdanweifhapi({
        orgNo: this.orgNo,
        // orgNo: '88018932',
        dateStr: this.radio3 == '日' ? this.value1 : this.radio3 == '月' ? this.value2 : this.value3,
        periodType:this.radio3 == '日' ? 'day' : this.radio3 == '月' ? 'month' : 'year'
      })
      this.tableData = res.data.list
      this.$refs.table.setCurrentRow(this.tableData[0]);
      this.loading=false
    },
    // 刷新列表
    shuaxin() {
      this.gettanglist()
      this.$message.success('列表刷新成功')
     },
    // 导出功能
    async daochu() {
      const orgName=this.qiyelist.filter(ele=>ele.bizOrgNo==this.orgNo)[0].bizOrgName
      const res = await exportdanweifhapi({
        orgName: orgName,
        orgNo: this.orgNo,
        dateStr: this.radio3 == '日' ? this.value1 : this.radio3 == '月' ? this.value2 : this.value3,
        periodType: this.radio3 == '日' ? 'day' : this.radio3 == '月' ? 'month' : 'year',
        isParams: true
      })
      const blobContent = new Blob([res])
      let url = window.URL.createObjectURL(blobContent)
      saveAs(url, '企业负荷分析.xls')
     },
    // 调节表格密度
    command(val) {
      if (val === '默认') {
        this.iissize = 'medium'
      } else if (val === '中等') {
        this.iissize = 'small'
      } else {
        this.iissize = 'mini'
      }
    },
    // 查询
    async submit() {
      this.dayyearmonth = this.radio3
      this.getmonth()
      await this.gettanglist()
      // this.getechartsdata()
      this.getzheecharts()
    },    // 获取折线图
    getzheecharts() {
      var chartDom = this.$refs.zexian
      var myChart = echarts.init(chartDom);
      var option;
      option = {
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data:this.dayyearmonth=='日'?timeArray:this.dayyearmonth=='月'?this.montharr:this.monthArray
        },
        yAxis: {
          name:'(kW)',
          type: 'value',
          axisLabel: {
            formatter: '{value}'
          }
        },
        grid:{ // 让图表占满容器
          top:"40px",
          left:"4%",
          right:"2%",
          bottom:"20px"
        },
        series: [
          {
            name: '实时负荷',
            type: 'line',
            smooth: true,
            data: this.echartarray,
            markPoint: {
              data: [
                { type: 'max', name: 'Max' },
                { type: 'min', name: 'Min' }
              ]
            },
            areaStyle: {
              normal: {
                //前四个参数代表位置 左下右上，如下表示从上往下渐变色 暗青色到亮青色，
                color: new echarts.graphic.LinearGradient(
                  0, 0, 0, 1,
                  [
                    { offset: 0, color: 'skyblue' },
                    { offset: 1, color: '#fff' }
                  ]
                )
              }
            },
            markLine: {
              data: [{ type: 'average', name: 'Avg' }]
            }
          }
        ]
      };
      option && myChart.setOption(option);
      window.addEventListener("resize", () => {
    //图表响应处理
        myChart.resize();
      });
    },
   // 获取当前时间戳
   gettime() {
      const date = new Date()
      const year = date.getFullYear() // 年
      const month = date.getMonth() + 1 // 月
      const day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
      this.value1 = year + '-' + month + '-' + day
      this.value2 = year + '-' + month
     this.value3 = year.toString()
    },
    // 获取当前选中的月份的日期
    getmonth() {
      const arr= this.value2.split('-')
    const daysInMonth = getDaysInMonth(arr[0], arr[1]);
    const numericDaysInMonth = daysInMonth.map(date => date.getDate()+'号');
      this.montharr = numericDaysInMonth
    },
    getechartsdata() {
        const echartarr= this.tableData.map(obj => {
        const { companyName, companyNo, ...newObj } = obj;
        return newObj;
        });
      const obj = echartarr[0]
      if (Object.keys(obj).length) {
      let minKey = Object.keys(obj).reduce((a, b) => a < b ? a : b);
      let minIndex = parseInt(minKey.slice(4));
      for (let i = minIndex - 1; i >= 1; i--) {
        let key = 'load' + i;
        if (!obj[key]) {
          obj[key] = 0;
        }
      }
      this.echartarray = Object.keys(obj)
          .sort((a, b) => parseInt(a.slice(4)) - parseInt(b.slice(4)))
          .map(key => obj[key]);
      } else {
        this.echartarray=[]
      }

    },
    handleCurrentChange(val) {
      const { companyName, companyNo, ...obj } = val
      // console.log(newObj);
      if (Object.keys(obj).length) {
        let minKey = Object.keys(obj).reduce((a, b) => a < b ? a : b);
      let minIndex = parseInt(minKey.slice(4));
      for (let i = minIndex - 1; i >= 1; i--) {
        let key = 'load' + i;
        if (!obj[key]) {
          obj[key] = 0;
        }
      }
      this.echartarray = Object.keys(obj)
          .sort((a, b) => parseInt(a.slice(4)) - parseInt(b.slice(4)))
        .map(key => obj[key]);
      } else {
         this.echartarray=[]
      }

        this.getzheecharts()
    }
  },
};
</script>

<style lang="scss" scoped>

.option{
  padding-left: 10px;
}
.bigbox{
  background-color:#f1f1f1;
  padding:10px;
  height:100%;
  
  .topbox{
    height:80px;
    background-color:#fff;
    padding: 20px;
  }
  .bodybox{
    margin-top: 10px;
    height: calc(100% - 90px);
    // height: 800px;
    background-color: #fff;
    padding: 20px;
    .tubiaobox{
      .zexian{
        height: 300px;
      }
    }
    .tablebox{
      margin-top: 20px;
      height: 50%;
      // height: 420px;
    }
  }
}
</style>